package com.library.servlet;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.library.dao.BookDAO;
import com.library.dao.BorrowRecordDAO;
import com.library.entity.Book;
import com.library.entity.BorrowRecord;
import com.library.entity.User;
import com.library.util.DateUtil;

/**
 * 借阅管理Servlet
 */
@WebServlet("/borrow")
public class BorrowServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String action = request.getParameter("action");
        HttpSession session = request.getSession(false);
        
        if (session == null || session.getAttribute("user") == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect("login.jsp");
            return;
        }
        
        User user = (User) session.getAttribute("user");
        
        if (action == null) {
            // 默认显示用户的借阅记录
            showUserRecords(request, response, user);
        } else if (action.equals("borrow")) {
            // 借阅图书
            borrowBook(request, response, user);
        } else if (action.equals("return")) {
            // 归还图书
            returnBook(request, response, user);
        } else if (action.equals("history")) {
            // 查看借阅历史
            showUserRecords(request, response, user);
        } else if (action.equals("current")) {
            // 查看当前借阅
            showCurrentRecords(request, response, user);
        } else {
            // 默认显示用户的借阅记录
            showUserRecords(request, response, user);
        }
    }
    
    // 显示用户的所有借阅记录
    private void showUserRecords(HttpServletRequest request, HttpServletResponse response, User user) 
            throws ServletException, IOException {
        BorrowRecordDAO recordDAO = new BorrowRecordDAO();
        List<BorrowRecord> records = recordDAO.getRecordsByUserId(user.getId());
        
        request.setAttribute("records", records);
        request.getRequestDispatcher("/user/borrow_history.jsp").forward(request, response);
    }
    
    // 显示用户当前的借阅记录
    private void showCurrentRecords(HttpServletRequest request, HttpServletResponse response, User user) 
            throws ServletException, IOException {
        BorrowRecordDAO recordDAO = new BorrowRecordDAO();
        List<BorrowRecord> records = recordDAO.getCurrentRecordsByUserId(user.getId());
        
        request.setAttribute("records", records);
        request.getRequestDispatcher("/user/current_borrow.jsp").forward(request, response);
    }
    
    // 借阅图书
    private void borrowBook(HttpServletRequest request, HttpServletResponse response, User user) 
            throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        
        // 检查图书库存
        BookDAO bookDAO = new BookDAO();
        Book book = bookDAO.getBookById(bookId);
        
        if (book == null) {
            // 图书不存在
            request.setAttribute("error", "图书不存在");
            response.sendRedirect("user/book?action=view&id=" + bookId);
            return;
        }
        
        if (book.getStock() <= 0) {
            // 图书库存不足
            request.setAttribute("error", "图书库存不足，无法借阅");
            response.sendRedirect("user/book?action=view&id=" + bookId);
            return;
        }
        
        // 检查用户是否已借阅该图书
        BorrowRecordDAO recordDAO = new BorrowRecordDAO();
        List<BorrowRecord> currentRecords = recordDAO.getCurrentRecordsByUserId(user.getId());
        
        for (BorrowRecord record : currentRecords) {
            if (record.getBookId() == bookId) {
                // 用户已借阅该图书
                request.setAttribute("error", "您已借阅该图书，请勿重复借阅");
                response.sendRedirect("user/book?action=view&id=" + bookId);
                return;
            }
        }
        
        // 创建借阅记录
        Date borrowDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(borrowDate);
        calendar.add(Calendar.DAY_OF_MONTH, 30); // 默认借阅30天
        Date returnDate = calendar.getTime();
        
        BorrowRecord record = new BorrowRecord(user.getId(), bookId, borrowDate, returnDate);
        
        // 添加借阅记录
        boolean recordAdded = recordDAO.addBorrowRecord(record);
        
        if (recordAdded) {
            // 更新图书库存
            boolean stockUpdated = bookDAO.updateBookStock(bookId, -1);
            
            if (stockUpdated) {
                // 借阅成功
                request.setAttribute("message", "借阅成功，请在 " + DateUtil.formatDate(returnDate) + " 前归还");
                response.sendRedirect("user/book?action=view&id=" + bookId);
            } else {
                // 更新库存失败，删除借阅记录
                // 实际应用中应该使用事务处理
                request.setAttribute("error", "借阅失败，请稍后再试");
                response.sendRedirect("user/book?action=view&id=" + bookId);
            }
        } else {
            // 添加借阅记录失败
            request.setAttribute("error", "借阅失败，请稍后再试");
            response.sendRedirect("user/book?action=view&id=" + bookId);
        }
    }
    
    // 归还图书
    private void returnBook(HttpServletRequest request, HttpServletResponse response, User user) 
            throws ServletException, IOException {
        int recordId = Integer.parseInt(request.getParameter("recordId"));
        
        // 获取借阅记录
        BorrowRecordDAO recordDAO = new BorrowRecordDAO();
        BorrowRecord record = recordDAO.getRecordById(recordId);
        
        if (record == null) {
            // 借阅记录不存在
            request.setAttribute("error", "借阅记录不存在");
            response.sendRedirect("borrow?action=current");
            return;
        }
        
        if (record.getUserId() != user.getId()) {
            // 借阅记录不属于当前用户
            request.setAttribute("error", "您无权归还此图书");
            response.sendRedirect("borrow?action=current");
            return;
        }
        
        if (record.getStatus() != 0) {
            // 图书已归还
            request.setAttribute("error", "该图书已归还");
            response.sendRedirect("borrow?action=current");
            return;
        }
        
        // 更新借阅记录状态
        boolean recordUpdated = recordDAO.returnBook(recordId);
        
        if (recordUpdated) {
            // 更新图书库存
            BookDAO bookDAO = new BookDAO();
            boolean stockUpdated = bookDAO.updateBookStock(record.getBookId(), 1);
            
            if (stockUpdated) {
                // 归还成功
                request.setAttribute("message", "图书归还成功");
                response.sendRedirect("borrow?action=current");
            } else {
                // 更新库存失败
                // 实际应用中应该使用事务处理
                request.setAttribute("error", "图书归还失败，请稍后再试");
                response.sendRedirect("borrow?action=current");
            }
        } else {
            // 更新借阅记录失败
            request.setAttribute("error", "图书归还失败，请稍后再试");
            response.sendRedirect("borrow?action=current");
        }
    }
}
